package com.ruoyi.system.report;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.HospitalSubscribeGroupPurchaseInspectionResults;
import com.ruoyi.system.domain.HospitalSubscribeGroupPurchaseMedicalExaminerInfo;
import com.ruoyi.system.domain.vo.HospitalSubscribeGroupPurchaseOrderVo;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@Service
public class MedicalReportService {

    // 样式常量
    private static final int PAGE_WIDTH = 750;
    private static final int PADDING_X = 40;
    private static final int PADDING_Y = 50;
    private static final int LINE_HEIGHT = 30;
    private static final int SECTION_SPACING = 25;
    private static final Color TITLE_COLOR = new Color(25, 113, 210);
    private static final Color SECTION_COLOR = new Color(15, 82, 186);
    private static final Color TEXT_COLOR = new Color(60, 60, 60);
    private static final Color BG_COLOR = new Color(249, 251, 253);
    private static final Color BORDER_COLOR = new Color(220, 230, 240);
    private static final Color NORMAL_COLOR = new Color(40, 167, 69);
    private static final Color ABNORMAL_COLOR = new Color(220, 53, 69);
    private static final Color WARNING_COLOR = new Color(255, 193, 7);

    public byte[] generateMedicalReportImage(HospitalSubscribeGroupPurchaseOrderVo vo) {
        for (HospitalSubscribeGroupPurchaseMedicalExaminerInfo info : vo.getExaminerInfoList()) {
            List<HospitalSubscribeGroupPurchaseInspectionResults> resultsList = info.getResultsList();
            for (HospitalSubscribeGroupPurchaseInspectionResults results : resultsList) {
                info.setCodeUrl(results.getCodeUrlInfo());
            }
        }

        try {
            // 动态计算图片高度
            int height = calculateDynamicHeight(vo);
            int titleY = PADDING_Y;

            // 创建缓冲图像
            BufferedImage image = new BufferedImage(PAGE_WIDTH, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();

            // 设置抗锯齿
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

            // 绘制背景
            g.setColor(BG_COLOR);
            g.fillRect(0, 0, PAGE_WIDTH, height);

            // 绘制边框
            g.setColor(BORDER_COLOR);
            g.setStroke(new BasicStroke(2));
            g.drawRoundRect(10, 10, PAGE_WIDTH - 20, height - 20, 20, 20);

            // 设置初始位置
            int x = PADDING_X;
            int y = PADDING_Y;

            // 绘制主标题
            g.setFont(new Font("Microsoft YaHei", Font.BOLD, 28));
            g.setColor(TITLE_COLOR);
            g.drawString("体检报告", x, y);
            y += 45;

            // 如果有二维码URL，绘制在右上角
            if (StringUtils.isNotBlank(vo.getCodeUrl())) {
                try {
                    // 从URL加载二维码图片
                    BufferedImage qrCodeImage = loadImageFromUrl(vo.getCodeUrl());

                    // 计算二维码位置（右上角）
                    int qrSize = 120;
                    int qrX = PAGE_WIDTH - PADDING_X - qrSize;
                    int qrY = PADDING_Y;

                    // 绘制二维码（自动缩放）
                    g.drawImage(qrCodeImage, qrX, qrY, qrSize, qrSize, null);

                    // 添加二维码文字说明
                    g.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
                    g.setColor(new Color(100, 100, 100));
                    String qrText = "订单验证二维码";
                    int textWidth = g.getFontMetrics().stringWidth(qrText);
                    g.drawString(qrText, qrX + (qrSize - textWidth)/2, qrY + qrSize + 15);

                } catch (Exception e) {
                    System.err.println("二维码加载失败: " + e.getMessage());
                    // 可以在这里绘制一个错误占位符
                    g.setColor(Color.RED);
                    g.drawString("[二维码加载失败]", PAGE_WIDTH - PADDING_X - 100, titleY + 20);
                }
            }

            // 绘制订单信息
            g.setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
            g.setColor(TEXT_COLOR);
            g.drawString("订单号：" + vo.getOrderNo(), x, y);
            y += LINE_HEIGHT;
            g.drawString("用户姓名：" + vo.getCompanyName(), x, y);
            y += LINE_HEIGHT;
            g.drawString("用户手机号：" + vo.getLinkmanPhone(), x, y);
            y += SECTION_SPACING + 10;

            // 绘制体检人信息
            List<HospitalSubscribeGroupPurchaseMedicalExaminerInfo> persons = vo.getExaminerInfoList();
            for (int i = 0; i < persons.size(); i++) {
                HospitalSubscribeGroupPurchaseMedicalExaminerInfo person = persons.get(i);

                // 绘制体检人标题
                g.setFont(new Font("Microsoft YaHei", Font.BOLD, 22));
                g.setColor(SECTION_COLOR);
                g.drawString((i + 1) + " 体检人信息：", x, y);
                y += LINE_HEIGHT + 5;

                // 绘制个人信息
                g.setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
                g.setColor(TEXT_COLOR);
                g.drawString("姓名：" + person.getName(), x, y);
                y += LINE_HEIGHT;
                g.drawString("手机号：" + person.getPhone(), x, y);
                y += LINE_HEIGHT;
                g.drawString("身份证号：" + person.getIdNumber(), x, y);
                y += LINE_HEIGHT;

                // 绘制体检结果标题
                g.drawString("体检结果：", x, y);
                y += LINE_HEIGHT;

                // 绘制体检人二维码（个人信息右侧）
                if (StringUtils.isNotBlank(person.getCodeUrl())) {
                    drawQrCode(g, person.getCodeUrl(),
                            PAGE_WIDTH - PADDING_X - 120, y - LINE_HEIGHT * 3,
                            "体检人二维码");
                }


                // 绘制体检结果项（支持动态项目名称和状态）
                List<HospitalSubscribeGroupPurchaseInspectionResults> checkItems = person.getResultsList();
                int itemX = x + 20;

                for (HospitalSubscribeGroupPurchaseInspectionResults item : checkItems) {
                    // 绘制项目名称
                    g.setColor(TEXT_COLOR);
                    g.drawString(item.getItemName() + "：", itemX, y);

                    // 根据状态绘制状态文本（带颜色）
                    int statusX = itemX + g.getFontMetrics().stringWidth(item.getItemName() + "：") + 5;

                    if (item.getInspectionResult().equals("无异常")) {
                        g.setColor(NORMAL_COLOR);
                    } else {
                        g.setColor(ABNORMAL_COLOR);
                    }

                    g.drawString(item.getInspectionResult(), statusX, y);
                    y += LINE_HEIGHT;
                }

                // 添加区块间距（最后一个不加）
                if (i < persons.size() - 1) {
                    // 绘制分隔线
                    g.setColor(new Color(230, 240, 250));
                    g.fillRect(x - 10, y + 10, PAGE_WIDTH - 2 * (PADDING_X - 10), 2);
                    y += SECTION_SPACING * 2;
                }
            }

            // 绘制总结信息
            y += 20;
            g.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
            g.setColor(SECTION_COLOR);
            g.drawString("报告总结：", x, y);
            y += LINE_HEIGHT;

            g.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
            g.setColor(TEXT_COLOR);
            g.drawString("• 本报告仅对本次体检结果负责", x, y);
            y += LINE_HEIGHT;
            g.drawString("• 如有异常项目，请及时就医复查", x, y);
            y += LINE_HEIGHT;
            g.drawString("• 报告日期：" + java.time.LocalDate.now().toString(), x, y);

            // 添加底部留白
            y += 30;

            // 释放资源
            g.dispose();

            // 转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            return baos.toByteArray();

        } catch (Exception e) {
            throw new RuntimeException("生成体检报告图片失败", e);
        }
    }

    private int calculateDynamicHeight(HospitalSubscribeGroupPurchaseOrderVo vo) {
        int height = PADDING_Y * 2;

        // 主标题高度
        height += 45;

        // 订单信息高度
        height += LINE_HEIGHT * 3;
        height += SECTION_SPACING + 10;

        // 体检人信息高度
        List<HospitalSubscribeGroupPurchaseMedicalExaminerInfo> persons = vo.getExaminerInfoList();
        for (HospitalSubscribeGroupPurchaseMedicalExaminerInfo person : persons) {
            height += LINE_HEIGHT + 5;
            height += LINE_HEIGHT * 3;
            height += LINE_HEIGHT;
            height += LINE_HEIGHT * person.getResultsList().size();

            // 区块间距（最后一个不加）
            if (persons.indexOf(person) < persons.size() - 1) {
                height += SECTION_SPACING * 2;
            }
        }

        // 报告总结高度
        height += 20;
        height += LINE_HEIGHT * 4;

        // 底部额外留白
        height += 50;

        return height;
    }

    public  BufferedImage loadImageFromUrl(String imageUrl) throws IOException {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 验证内容类型
            String contentType = connection.getContentType();
            if (!contentType.startsWith("image/")) {
                throw new IOException("URL不是图片类型");
            }

            return ImageIO.read(connection.getInputStream());

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private void drawQrCode(Graphics2D g, String qrUrl,
                            int x, int y, String caption) {
        try {
            BufferedImage qrImage = loadImageFromUrl(qrUrl);
            int qrSize = 100;

            // 绘制二维码
            g.drawImage(qrImage, x, y, qrSize, qrSize, null);

            // 绘制说明文字
            g.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
            g.setColor(new Color(100, 100, 100));
            int textWidth = g.getFontMetrics().stringWidth(caption);
            g.drawString(caption, x + (qrSize - textWidth)/2, y + qrSize + 12);

        } catch (Exception e) {
            System.err.println("二维码加载失败: " + qrUrl);
            g.setColor(Color.RED);
            g.drawString("[二维码加载失败]", x, y + 15);
        }
    }
}